<?php
namespace modules\resource\services;

use modules\resource\ResourceException;

Class DownloadService
{
	public static function checkExist($name)
	{
		static $fileConfig;
		if (empty($fileConfig)) {
			$path = __DIR__ . '/../config/FileConfig.php';
			$fileConfig = require_once($path);
		}
		if (!in_array($name, $fileConfig['limitFileList'])) {
			ResourceException::throw(ResourceException::FILE_NOT_EXIST, '文件配置有误');
		}
	}
	public static function file($name)
	{
		self::checkExist($name);
		$path = PATH_BASE . 'web/file/';
		if (!file_exists($path . $name)) {
			ResourceException::throw(ResourceException::FILE_NOT_EXIST, '文件不存在');
		}
		self::download($name, $path);

	}

	//文件下载任务
	public static function download($name,$path)
	{
		$filePath = $path . $name;
		 //这里要注意下载也需要转码iconv
		$filePath  = iconv('utf-8','gbk',$filePath);
		$name      = iconv('utf-8','gbk',$name);
		$file_size = filesize($filePath);
		$file      = fopen($filePath,'r');
		
		// 必要的三个头文件
		header('Content-type: application/octet-stream');
		header("accept-length:$file_size");
		header("Content-Disposition:attachment;filename=$name");
			while(!feof($file)){
				$stream = fread($file,1024);
				echo $stream;
			}
		fclose($file);
	}
}